from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import redirect, reverse
from django.shortcuts import render
import json
from django.views.decorators.csrf import csrf_exempt
from .models import BusActrssType

from elasticsearch_dsl.connections import connections
from elasticsearch import Elasticsearch

connections.create_connection(hosts=['localhost'])
client = Elasticsearch(hosts=['localhost'])

@csrf_exempt # 设置可接收post请求
def search_suggestion(request):
    keywords = request.POST.get('keywords')
    res = {
        'count': 0
    }
    if keywords:
        s = BusActrssType.search()
        s = s.suggest('get_result', keywords, completion={
            'field': 'suggest',
            'fuzzy': {
                'fuzziness': 0
            },
        })
        suggestions = s.execute_suggest()

        options = suggestions.get_result[0].options
        list = []
        res['count'] = len(options)
        for option in options:
            source = option._source
            list.append({
                'name': source['actress_names'],
                'url': source['actress_links'],
                'icon': source['image_url']
            })
        res['result'] = list
    else:
        res['result'] = keywords

    # res['code'] = 0
    return HttpResponse(json.dumps(res), content_type='application/json')

@csrf_exempt # 设置可接收post请求
def search_actresses(request): # 搜索演员
    keywords = request.POST.get('keywords')
    foo = {
        'total': 0,
        'result': None
    }
    if keywords:
        response = client.search(
            index='bus',
            doc_type='actress',
            body={
                "query": {
                    "bool": {
                        "must": {
                            "match": {
                                "actress_names": keywords
                            }
                        }
                    }
                },
                "_source": ["actress_names", "actress_links", "image_url"]
            }
        )

        hits = response['hits']
        total = hits['total']
        sub_hits = hits['hits']
        result = []
        for sub_hit in sub_hits: # 这里遍历取值 是否可以自定义字段名 是否可以设置隐藏系统字段
            source = sub_hit['_source']
            result.append(source)
        foo['total'] = total
        foo['result'] = result

    return HttpResponse(json.dumps(foo), content_type='application/json')

@csrf_exempt
def search_video(request): # 搜索影片
    keywords = request.POST.get('keywords')
    foo = {
        'total': 0,
        'result': None
    }
    if keywords:
        response = client.search(
            index='bus',
            doc_type='video',
            body={
                "query": {
                    "bool": {
                        "must": {
                            "match": {
                                "title": keywords
                            }
                        }
                    }
                },
                "_source": [
                    "title",
                    "url",
                    "cover",
                    "image_url",
                    "code",
                    "pub_date",
                    "v_len",
                    "director",
                    "producers",
                    "publisher",
                    "series",
                    "category",
                    "summary_small_image",
                    "summary_large_image",
                    "actress"
                ]
            }
        )

        hits = response['hits']
        total = hits['total']
        sub_hits = hits['hits']
        result = []
        for sub_hit in sub_hits:  # 这里遍历取值 是否可以自定义字段名 是否可以设置隐藏系统字段
            source = sub_hit['_source']
            result.append(source)
        foo['total'] = total
        foo['result'] = result

    return HttpResponse(json.dumps(foo), content_type='application/json')

def test(request):
    response = client.search(
        index='bus',
        doc_type='actress',
        body={
            "query": {
                "match_all": { }
            },
            "_source": ["director"]
        }
    )

    hits = response['hits']

    total_nums = response['hits']['total']
    return HttpResponse(json.dumps(hits), content_type='application/json')

